# -*- coding: utf-8 -*-
from common.emqx.emqx_client import EMQXClient
import json
import time

TOPIC_ORANGEPI_TEMP = "orangepi_temp"

# 自定义消息处理回调
def handle_message(client, userdata, msg):
    try:
        data = json.loads(msg.payload)
        print(f"[应用] 收到结构化数据: {data}")
        # 检查消息是否以"send"开头
        if data.get('requestType') == 'send':
            print("[应用] 检测到发送指令，准备发送响应消息...")
            # 使用 with 语句确保 sender 连接
            with sender:
                sender.publish(
                    topic=TOPIC_ORANGEPI_TEMP,
                    payload={"requestId":data.get('requestId'),"requestType":"receive","type": "temp", "value": "47"},
                    qos=1
                )
            print("[应用] 响应消息已发送")
    except json.JSONDecodeError as e:
        print(f"[应用] JSON解析失败: {e}，原始内容: {msg.payload.decode()}")
    except Exception as e:
        print(f"[应用] 未知错误: {e}")

# 初始化接收客户端
receiver = EMQXClient(
    client_id="orangepi_mqreceive",
    broker="192.168.1.42",
    port=8083
)

sender = EMQXClient(
    client_id="orangepi_mqsender",
    broker="192.168.1.42",
    port=8083
)

# 注册自定义回调
receiver.register_message_callback(handle_message)

with receiver:
    receiver.subscribe(TOPIC_ORANGEPI_TEMP, qos=1)
    while True:  # 保持运行
        time.sleep(1)